from django.shortcuts import render, get_object_or_404,redirect
from django.views.decorators.http import require_POST
from .models import GunStatus,Pile
from django.urls import reverse
from django.contrib import messages
from .connectors import pile_connections

@require_POST
def update_gun_status(request, pile_id):
    pile = get_object_or_404(Pile, pk=pile_id)
    for gun_status in pile.gun_statuses.all():
        new_status = request.POST.get(f'status_{gun_status.id}')
        new_plugged = request.POST.get(f'plugged_{gun_status.id}')

        if new_status and new_plugged:
            gun_status.status = new_status
            gun_status.plugged_in = new_plugged
            gun_status.save()

    # 更新Gun对象中的状态（如果连接存在）
    if pile_id in pile_connections:
        connector = pile_connections[pile_id]
        with connector.lock:
            for gun_status in pile.gun_statuses.all():
                if gun_status.gun_id in connector.guns:
                    connector.guns[gun_status.gun_id].pile_sta = gun_status.status
                    connector.guns[gun_status.gun_id].pile_on = gun_status.plugged_in

    messages.success(request, '枪状态已更新')
    return redirect('iot:manage_gun_status', pile_id=pile_id)

def manage_gun_status(request, pile_id):
    pile = get_object_or_404(Pile, pk=pile_id)
    gun_statuses = pile.gun_statuses.all()

    # 自动创建枪状态（如果不存在）
    if not gun_statuses.exists() and pile.gun_count > 0:
        pile.create_gun_statuses()
        gun_statuses = pile.gun_statuses.all()

    # 获取 admin URL 的前缀
    changelist_url = reverse('admin:iot_ykc_simulator_pile_changelist')

    return render(request, 'admin/gun_status_management.html', {
        'pile': pile,
        'gun_statuses': gun_statuses,
        'title': '枪状态管理',
        'changelist_url': changelist_url  # 传给模板使用
    })